package com.yehongyu.mytools.fileio;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

public class ListFiles {
	
	/** 日志记录 */
	private final static Logger logger = Logger.getLogger(ListFiles.class);
	
	private static String OUT_PATH = System.getProperty("user.dir") + "/logdir/";
	private static String IN_PATH = System.getProperty("user.dir") + "/src/main/java";

	public static void main(String[] args) {
		writeToTxt();
	}
	
	/**
	 * 将目录下的文件列表写到文本
	 */
	public static void writeToTxt() {
		try {
			File saveFile = new File(OUT_PATH + "filelist.txt");
			FileWriter fw = new FileWriter(saveFile);
			fw.write(listFile(ClassLoader.getSystemResource("").getPath(), null)
					.toString());
			fw.write(listFile(IN_PATH, null).toString());
			fw.close();
		} catch (IOException e) {
			logger.error("IO error!", e);
		}
	}
	
	/**
	 * 列出指定目录下的所有文件
	 * @param rp 指定目录
	 * @param listFileStr 文件列表StringBuilder
	 * @return 文件列表StringBuilder
	 */
	public static StringBuilder listFile(String rp,StringBuilder listFileStr) {
		if(listFileStr==null) listFileStr = new StringBuilder();
		File file = new File(rp);
		File list[] = file.listFiles();
		for (int i = 0; i < list.length; i++) {
			try {
				if (list[i].isDirectory()) {
					listFile(list[i].toString(),listFileStr);
				} else {
					listFileStr.append(list[i].getAbsolutePath() + "\r\n");
					if(logger.isDebugEnabled()){
						logger.debug(list[i].getAbsolutePath());
					}
				}
			} catch (Exception ex) {
				listFileStr.append("Access deny：" + list[i].getAbsolutePath() + "\r\n");
				logger.error("Access deny：" + list[i].getAbsolutePath(),ex);
			}
		}
		return listFileStr;
	}

}
